﻿using ElectronicShoppingMall.Service.Services.Enterprise;
using Extension;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace ElectronicShoppingMall.Web.Back.Filter
{
    public class EmployeePermissionAttribute : AuthorizationFilterAttribute
    {
        private MenuService _serviceMenu = new MenuService();
        public string PermissionCode { get; set; }
        public override void OnAuthorization(HttpActionContext actionContext)
        {            //如果用户方位的Action带有AllowAnonymousAttribute，则不进行授权验证
            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
            {
                return;
            }
            string auth = actionContext.Request.Headers.Authorization.ToString();
            var verifyResult = CheckPermissions( ExtensionMethods.GetEmployeeUserObject(auth).EmployeeId);

            if (!verifyResult)
            {                //如果验证不通过，则返回401错误，并且Body中写入错误原因
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("没有权限"));
            }
        }

        private bool CheckPermissions(int employeeId)
        {
            try
            {
                var permissions = _serviceMenu.GetMenuPermission(employeeId);
                var permission = permissions.SingleOrDefault(p => p.Code == PermissionCode);
                if (permission != null)
                {
                    return true;
                }
                else {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
    }
}